<?php
// +----------------------------------------------------------------------
// | 平台软终端验证
// +----------------------------------------------------------------------
// | Author: TongBC <501468940@qq.com>
// +----------------------------------------------------------------------
// | Date  : --/--/--
// +----------------------------------------------------------------------
include_once('/var/www/html/new/com.inc.php');
include_once('/var/www/html/new/d/class/Terminal_Check_Socket.class.php');


// 身份验证 只有供应商、商户、管理员可以进行验证
if(!isset($_SESSION['sid'])) exit('{"status":"fail","msg":"请先登录后再操作","code":0}');
if(!in_array($_SESSION['sdtype'], array(0,2,3,6,9))) exit('{"status":"fail","msg":"身份不合法"}');

$ac = $GLOBALS['_ac'];
$pw = $GLOBALS['_pw'];
$s  = new SoapClient(null,array("location" => "http://localhost/open/openService/pft_insideMX.php","uri" => "www.16u.com?ac_16u=$ac|pw_16u=$pw|auth_16u=true"));


	
// 接收数据
$salerid = $_REQUEST['salerid'] + 0;// 商户ID
$voucher = $_REQUEST['voucher'];// 凭证码


// 验证部分
if(isset($_REQUEST['data'])){
	
	$recv = json_decode($_REQUEST['data'], true);
	
	$salerid = $recv['salerid'];
	$voucher = $recv['voucher'];
	
	$ordernum = $recv['ordernum'];
	$verify = new PsVerfiy($s, $salerid);
	$orders = $verify->information($ordernum);

	// 是否采用新服务器验证
	$order  = current($orders);
	$landid = $order['landid'] + 0;
	$uucode = $order['code'];
	
	$memberSID = $_SESSION['sid'];
	$memberID  = $_SESSION['memberID'];
	
	$sql = "select terminal,terminal_type,salerid from uu_land where id=$landid limit 1";
	$GLOBALS['le']->query($sql);
	if(!$GLOBALS['le']->fetch_assoc()) exit('{"status":"fail","msg":"未找到景区"}');
	$terminal_inum = $GLOBALS['le']->f('terminal');
	$terminal_type = $GLOBALS['le']->f('terminal_type');
	
	$changeTickets = array(); $change_f = false;
	if($order['ptype']!='F' && $order['ptype']!='C'){
		foreach($order['tickets'] as $row){
			
			$changeTickets[] = $row['ordernum'];
			$changeTickets[] = $recv['list'][$row['ordernum']];
			if($recv['list'][$row['ordernum']]==$row['tnum']) continue;
			$change_f = true;
			
			if($terminal_type==0){// 老验证模式
				$tnum = $recv['list'][$row['ordernum']];
				$totalprice = $row['tprice'] * $tnum;
				$ret = $s->Order_Change_Pro($row['ordernum'], $tnum, $totalprice, 0, $_SESSION['memberID']);
				if($ret==100){
					$logs = '['.$row['ordernum'].']部分验证进行改单,操作人['.$_SESSION['memberID'].']';
					PsVerfiy::logs($logs, 'terminal_check_change');
				}
			}
		}
	}
	
	if($terminal_type==1){// 使用新服务器
		$tc = Terminal_Check_Socket::connect();
		if($change_f && $order['ptype']!='F'){// 改单验证
			$chResult = $tc->Terminal_ChangeCheck_In_Voucher($terminal_inum, $salerid, $uucode, count($order['tickets']), $changeTickets);
			$checkData = json_encode(array($terminal_inum, $salerid, $uucode, count($order['tickets']), $changeTickets));
			$logs = "[$ordernum]改单验证,操作人[$memberID],数据[$checkData],结果[".json_encode($chResult)."]";
		}else{
			
			$chkIns = ($memberSID==1) ? '499':'260';
			if($order['status']==2 && $memberSID==1) $chkIns = 498;
			if($order['ptype']=='F'){
				$chResult = $tc->Terminal_Check_In_Order($terminal_inum, $salerid, $ordernum);
			}else{
				$chResult = $tc->Terminal_Check_In_Voucher($terminal_inum, $salerid, $uucode, array('vCmd'=>$chkIns));
			}
			$checkData = json_encode(array($terminal_inum, $salerid, $uucode, array('vCmd'=>$chkIns)));
			$logs = "[$ordernum]订单验证,操作人[$memberID],数据[$checkData],结果[".json_encode($chResult)."]";
			$ticket_count = count($order['tickets']);
			
			if($order['ptype']=='F'){// 同一景区不同门票被打包成套票需循环验证
				if($ticket_count>1 && isset($chResult['multi'])){
					foreach($chResult['tickets'] as $row){
						// echo rtrim($row['ticket_code']);
						// echo $row['ticket_code'];
						$tc = new Terminal_Check_Socket();  // if($_SESSION['sid']==3385) $chkIns = 499;
						$chResult_multi = $tc->Terminal_Check_In_Voucher($terminal_inum, $salerid, $row['ticket_code'], array('vCmd'=>$chkIns));
						$checkData = json_encode(array($terminal_inum, $salerid, $row['ticket_code'], array('vCmd'=>$chkIns)));
						$logs_multi = "[$ordernum]---订单验证,操作人[$memberID],数据[$checkData],结果[".json_encode($chResult_multi)."]";
						PsVerfiy::logs($logs_multi, 'terminal_check_pack');
						if($chResult_multi['state']=='fail') exit('{"status":"fail","msg":"'.$chResult_multi['msg'].'---"}');
					}
				}
			}
		}

		// 员工更新操作日志
		if($_SESSION['dtype']==6){
			$sql = "insert into pft_d_operation_rec set fid=$memberID,sid=$memberSID,daction='订单验证,订单号【".$ordernum."】',rectime=now()";
			$GLOBALS['le']->query($sql);
		}

		PsVerfiy::logs($logs, 'terminal_check_new');
		if($chResult['state']=='success') exit('{"status":"success","msg":"验证成功"}');
		exit('{"status":"fail","msg":"'.$chResult['msg'].'"}');
	}
	
	// 进行验证
	$rtime = ($memberSID==1) ? $recv['rtime']:'';
	$code = $orders[$ordernum]['code'];
	$simxml = $verify->check($code, $rtime);
	
	if(is_numeric($simxml)) exit('{"status":"fail","msg":"'.$verify->errCode[$simxml].'"}');
	$simxml_o = simplexml_load_string($simxml);
	$ordernum = $simxml_o->Rec->UUordernum;// 已验证订单
	$uuino    =(string)$result->Rec->UUino;// 验证流水号
	
	// 员工更新操作日志
	if($_SESSION['dtype']==6){
		$sql = "insert into pft_d_operation_rec set fid=$memberID,sid=$memberSID,daction='订单验证,订单号【".$ordernum."】',rectime=now()";
		$GLOBALS['le']->query($sql);
	}
	
	// 记录日志
	PsVerfiy::logs("[$ordernum]订单验证,操作人[$memberID]");
	exit('{"status":"success","msg":"验证成功"}');
}






if($salerid==0 || ($_REQUEST['voucher']+0)==0) exit('[]');

// 获取订单信息部分
$verify = new PsVerfiy($s, $salerid);
if(strlen($voucher)==6){// 凭证码

	$code = $voucher;
	$ordernum = $verify->reverse($voucher);// 反查订单号
    $send = array();
    echo json_encode(array('status'=>'success','orders'=>$verify->information($ordernum)));
	
}elseif(strlen($voucher)==11 && is_numeric($voucher)){// 手机号

	$mobile = $voucher;
	$send = array();
	$status = ($_SESSION['sid']==1) ? '0|2':'0';// 0 未验证 2 已过期
	$xmlStr = $s->Order_Globle_Search($salerid,'','','','','','','','','','','','','',$mobile, $status,'','',1,0,0,100,'','','','','','','','','',0,0);
	$simxml = simplexml_load_string($xmlStr);
	$unique_a = array();// 多级转分校重复
	$unique_b = array();// 子票防止重复
	foreach($simxml->Rec as $row){
		
		if(isset($unique_a[(string)$row->UUordernum])) continue;
		$unique_a[(string)$row->UUordernum] = (string)$row->UUordernum;	
		
		if((string)$row->UUpack_order!=0){
			if(isset($unique_b[(string)$row->UUpack_order])) continue;
			$unique_b[(string)$row->UUpack_order] = (string)$row->UUpack_order;	
		}
		$send = array_merge($send, $verify->information((string)$row->UUordernum));
		
	}
	echo json_encode(array('status'=>'success','orders'=>$send));
	
}else{// 身份证

	$idCard = $voucher;
	$simxml = $verify->checkIDCard('', $voucher);
	$simxml_o = simplexml_load_string($simxml);
	$send = array();
	$unique = array();// 子票防止重复
	foreach($simxml_o->Rec as $row){
		if((string)$row->UUpack_order!=0){
			if(isset($unique[(string)$row->UUpack_order])) continue;
			$unique[(string)$row->UUpack_order] = (string)$row->UUpack_order;	
		}
		$send = array_merge($send, $verify->information((string)$row->UUordernum));
	}
	echo json_encode(array('status'=>'success','orders'=>$send));
}




class PsVerfiy{
	
	public $inside = null;// 内部接口
	public $salerid = 0;  // 商户账号
	public $errCode = array(
		'105'=>'找不到订单',
		'121'=>'订单状态出错,订单已验证或已过期',
		'119'=>'订单状态出错,已取消或其他状态',
		'521'=>'验证间隔时间未到',
		'133'=>'游玩时间未到',
		'134'=>'游玩时间已过',
		'118'=>'终端服务器无响应',
		'1070'=>'订单未支付',
	);

	
	public function __construct($s, $salerid){
		$this->inside = $s;
		$this->salerid = $salerid;
	}
	
	// 验证
	public function check($voucher, $rtime=''){
		return $this->inside->Terminal_Check_In($this->salerid, $voucher, $rtime);
	}
	
	
	
	// 身份证获取所有订单信息
	public function checkIDCard($username, $idCard=null, $rtime=null){
		return $this->inside->Terminal_Check_IDcard($this->salerid, $username, $idCard, $rtime);
	}
	
	
	// 通过商户6位账号和凭证码反查订单
	public function reverse($voucher, $sid=0){
		$salerid = $this->salerid;
		if($sid==0) $sid = $_SESSION['sid'];
		$ordernum = $this->inside->Code_Verify_Order($salerid, $voucher, $sid);
        return $ordernum;
	}
	

	
	// 获取订单信息
	public function information($orderId='', $mobile=''){
		
		$init_order = $orderId;
		$sendData = array();
		$salerid = $this->salerid;
		$orderStatus = ($_SESSION['sid']==1) ? '0|2':'0';// 0 未验证 2 已过期
		if($orderId=='') return $sendData;
		$xmlStr = $this->inside->Order_Globle_Search($salerid,'','','','','','','','','','','',$orderId,'','', $orderStatus,'','',1,0,0,1,'','','','','','','','','',0,0);
		$simxml = simplexml_load_string($xmlStr);

		
		// 订单查找可能联票只能再次获取
		if($orderId!='' &&(string)$simxml->Rec->UUconcat_id==(string)$simxml->Rec->UUordernum){
			$xmlStr = $this->inside->Order_Globle_Search($salerid,'','','','','','','','','','','',$orderId,'',$mobile, $orderStatus,'','',1,0,0,100,'','','','','','','','','',1,0);
			$simxml = simplexml_load_string($xmlStr);
		}

		// 套票可能同一产品的两个不同子票会一起验证，所以都要显示出来
		if((string)$simxml->Rec->UUpack_order!=0){
			// if((string)$simxml->Rec->UUstatus!=0) return $sendData;
			$orderId = (string)$simxml->Rec->UUpack_order;
			$xmlStr = $this->inside->Order_Globle_Search($salerid,'','','','','','','','','','','',$orderId,'',$mobile, $orderStatus,'','',1,0,0,100,'','','','','','','','','',0,2);
			$simxml = simplexml_load_string($xmlStr);
		}
		
		$sets_f = array();
		$same_f = 0;
		$isFirst = true;
		$isPack = false;
		foreach($simxml->Rec as $order){

			if(in_array((string)$order->UUordernum, $sets_f)) continue;// 已经设置过，防止admin重复显示

			if((string)$order->UUpack_order!=0){// 套票
				/* // 非第一次设置并且lid不跟第一样，并且不是这次查找的订单
				if($same_f!=0 && (string)$order->UUlid!=$same_f && (string)$order->UUordernum!=$init_order) continue;// 不是统一产品底下的两个产品不显示
				
				if($order->UUstatus!=0) continue;// 顺序问题
				$same_f = (string)$order->UUlid;
				if($isFirst){// 酒店
					$orderId = (string)$order->UUordernum;
					$isFirst = false;
				}
				$orderId = (string)$order->UUordernum;
				// 第二次是要的的订单，说明之前的跟这次不一样，清空
				if(!$isFirst && (string)$order->UUordernum==$init_order){
					$sendData = array();
				} */
				if((string)$order->UUsalerid!=$salerid) continue;
				if((string)$order->UUstatus==1) continue;
				$orderId = (string)$order->UUordernum;
			}elseif($order->UUconcat_id!=0){// 联票
				$concat = (string)$order->UUconcat_id;
				$ordernum = (string)$order->UUordernum;
				$orderId = ($concat==$ordernum) ? $ordernum:$concat;
				if($concat!=$ordernum && !isset($sendData[$orderId]['ordernum'])) continue;
			}else{
				
				$orderId = (string)$order->UUordernum;
			}

			
			if(!isset($sendData[$orderId]['ordernum'])){
				$sendData[$orderId]['ordernum'] = $orderId;//  订单号
				$sendData[$orderId]['ordername'] = (string)$order->UUordername;// 取票人姓名
				$sendData[$orderId]['ordertel'] = (string)$order->UUordertel;// 取票人手机
				$sendData[$orderId]['ordertime'] = (string)$order->UUordertime;// 下单时间
				$sendData[$orderId]['begintime'] = (string)$order->UUbegintime;// 游玩时间
				$sendData[$orderId]['pmode'] = (string)$order->UUpmode;
				$sendData[$orderId]['status'] = (string)$order->UUstatus;
				$sendData[$orderId]['code'] = (string)$order->UUcode;
				$sendData[$orderId]['paystatus'] = (string)$order->UUpaystatus;
				$sendData[$orderId]['ptype'] = (string)$order->UUp_type;
				$sendData[$orderId]['landid'] = (string)$order->UUlid;
				
				// 已过期的订单从 2015-06-30 开始不会显示已过期，订单显示 未使用 abc-2015-07-01
				if((int)$order->UUstatus==0){
					if((strtotime((string)$order->UUendtime)+86400)<time())
						$sendData[$orderId]['status'] = 2;
				}
				
				// 对于admin 过期产品返回使用开始时间
				if($_SESSION['sid']==1 && $sendData[$orderId]['status']){
					$sendData[$orderId]['endtime'] = (string)$order->UUendtime;
				}
				
				// 套票不允许改单验证
				if((string)$order->UUpack_order!=0){
					$sendData[$orderId]['ptype'] = 'F';
				}
			}
			
			$sendData[$orderId]['tickets'][] = array(
				'name'=>(string)$order->UUttitle,
				'tnum'=>(int)$order->UUtnum,
				'ordernum'=>(string)$order->UUordernum,
				'tprice'=>(string)$order->UUtprice
			);
			$sets_f[] = (string)$order->UUordernum;

		}
		return $sendData;
	}
	
	public static function logs($content, $file='terminal_check'){
		$fullpath = '/var/www/html/new/d/logs/terminal_check/'.$file.date('Ymd').'.txt';
		$fp = fopen($fullpath,"a");
		flock($fp, LOCK_EX);
		fwrite($fp,date("Y-m-d H:i:s").":".$content."\n");
		flock($fp, LOCK_UN);
		fclose($fp);
	}
}





